<template>
  <view class="normal-login-container">
    <view class="logo-content align-center justify-center flex">
      <image style="width: 80rpx;height: 50rpx;" :src="globalConfig.appInfo.logo" mode="widthFix">
      </image>
      <text class="title">机房巡检</text>
    </view>
	<!-- 注册类型选择 -->
    <view class="login-form-content">
	  <u-tabs :list="typeList" @click="clickType"
	      lineWidth="20"
	      lineHeight="4"
	      :lineColor="`red`"
	      :activeStyle="{color: '#303133', fontWeight: 'bold', transform: 'scale(1.05)'}"
	      :inactiveStyle="{color: '#606266', transform: 'scale(1)'}"
	      itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;"
	  ></u-tabs>
	  
	  <view class="input-item xrequired flex align-center">
		<view class="iconfont icon-xingming icon"></view>
		<input v-model="registerForm.nickName" class="input" type="text" :placeholder="baseInfo.nickNameText" maxlength="30" />
	  </view>
	  <view class="input-item xrequired flex align-center">
	    <view class="iconfont icon-shoujihaoma icon"></view>
		<input disabled v-model="registerForm.username" class="input" type="tel" placeholder="用户手机号无法获取" maxlength="11" />
	  </view>
	  <view class="input-item xrequired flex align-center">
	    <view class="iconfont icon-ziyuanxhdpi icon"></view>
	    <input v-model="registerForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" />
	  </view>
	  <view class="input-item xrequired flex align-center">
	    <view class="iconfont icon-querenmima icon"></view>
	    <input v-model="registerForm.confirmPassword" type="password" class="input" placeholder="请输入确认密码" maxlength="20" />
	  </view>
	  <view v-if="false" class="input-item xrequired flex align-center">
			<view class="iconfont icon-shenfenzhenghao icon"></view>
			<input v-model="registerForm.cardNo" class="input" type="idcard" :placeholder="baseInfo.idCodeText" maxlength="18" />
	  </view>
	  <view v-if="false" class="input-item xrequired flex align-center">
			<view class="iconfont icon-shoujihaoma icon"></view>
			<input v-model="registerForm.phonenumber" class="input" type="tel" :placeholder="baseInfo.phoneNumText" maxlength="11" />
	  </view>
	  <view class="input-item flex align-center">
	    <view class="iconfont icon-shequ icon"></view>
	  		<input v-model="registerForm.address" class="input" type="text" placeholder="请输入居住地址,如xxx社区xxx小区x栋" maxlength="255" />
	  </view>
	  <!-- <view class="input-item xrequired flex align-center">
	  		<view class="iconfont icon-shequ icon"></view>
			<input v-model="communityLable" class="input" type="text" 
				@click="chooseAddress" :disabled="true" placeholder="请选择所属网格" maxlength="30" />
	  		<u-picker :show="showChooseAddress" ref="uPicker" :columns="addressColumns" keyName="label"
	  					@confirm="confirmAddress" @cancel="cancelAddress" @change="changeAddress"></u-picker>
	  </view> -->
	  
	  <view class="input-item xrequired flex align-center" style="width: 60%;margin: 0px;" v-if="captchaEnabled">
	    <view class="iconfont icon-yanzhengma icon"></view>
	    <input v-model="registerForm.code" type="text" class="input" placeholder="请输入验证码" maxlength="4" />
	    <view class="login-code"> 
	      <image :src="codeUrl" @click="getCode" class="login-code-img"></image>
	    </view>
	  </view>
      <view class="action-btn">
        <button @click="handleRegister()" class="register-btn cu-btn block bg-blue lg round">注册</button>
      </view>
    </view>
    <view class="xieyi text-center">
      <text @click="handleUserLogin" class="text-blue">使用已有账号登录</text>
    </view>
  </view>
</template>

<script>
  import { getCodeImg, register } from '@/api/login'
  // import { getCommunityInfoTreeList } from '@/api/community/community'
  import { decryptData } from "@/utils/aes-util"
  
  export default {
    data() {
      return {
		globalConfig: getApp().globalData.config,
		typeList: [{name: '个人'}, {name: '企业'}],
		isEnterprise: false,
		baseInfo: {
			nickNameText: "请输入真实姓名",
			phoneNumText: "请输入手机号码",
			idCodeText: "请输入身份证"
		},
		// 所属社区
		showChooseAddress: false,
		addressColumns: [],
		addressData: [],  
		// 验证码
        codeUrl: "",
        captchaEnabled: true,
		// 所属网格显示
		communityLable: "",
        // 注册form
        registerForm: {
          username: "",
          password: "",
          confirmPassword: "",
          code: "",
          uuid: "",
		  nickName: "",
		  phonenumber: "",
		  cardNo: "",
		  locationId: "",
		  userType: "01",
		  address: "",
        }
      }
    },
	

	/**
	 * 接受上个页面传递的参数
	 * option为object类型，会序列化上个页面传递的参数
	 */
	onLoad: function (option) { 
	  // 1.将拿到的 phone 进行解密操作
	  let dePhone = '';
	  if(!this.$Utils.isNull(option.phone)) {
		  dePhone = decryptData(option.phone)
		  this.registerForm.username = dePhone
	  }
	},
	
    created() {
      this.getCode()
	  // this.getCommunityData()
    },
    methods: {
		// 获取图形验证码
		getCode() {
		  getCodeImg().then(res => {
			this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
			if (this.captchaEnabled) {
			  this.codeUrl = 'data:image/gif;base64,' + res.img
			  this.registerForm.uuid = res.uuid
			}
		  })
		},
		
		// 切换注册类型，个人/企业
		clickType(e) {
			if(e.name == '个人') {
				this.isEnterprise = false;
				this.registerForm.userType = "01";
				this.baseInfo.nickNameText = "请输入真实姓名";
				// this.baseInfo.phoneNumText = "请输入手机号码";
				// this.baseInfo.idCodeText = "请输入身份证";
			}
			else if(e.name == '企业') {
				this.isEnterprise = true;
				this.registerForm.userType = "02";
				this.baseInfo.nickNameText = "请输入企业名称";
				// this.baseInfo.phoneNumText = "请输入经办人手机号码";
				// this.baseInfo.idCodeText = "请输入企业信用代码";
			}
		},
		
		// 获取社区数据
		async getCommunityData() {
			getCommunityInfoTreeList().then(res => {
				const dataArr = res.data
				const oneArr = []
				const twoArr = []
				const defaultArr = []
				
				const item = {}
				item.label = dataArr[0].infoName
				item.value = dataArr[0].infoId
				oneArr.push(item)
				const children = dataArr[0].children
				for(let i=0; i<children.length; i++) {
					const itemTwo = {}
					itemTwo.label = children[i].infoName
					itemTwo.value = children[i].infoId
					twoArr.push(itemTwo)
					
					const threeArr = []
					for(let j=0; j < (children && children[i] && children[i].children && children[i].children.length); j++) {
						const itemThree = {}
						itemThree.label = children[i].children[j].infoName
						itemThree.value = children[i].children[j].infoId
						threeArr.push(itemThree)
						if(i == 0) {
							defaultArr.push(itemThree)
						}
					}
					this.addressData.push(threeArr)
				}
				this.addressColumns.push(oneArr)
				this.addressColumns.push(twoArr)
				this.addressColumns.push(defaultArr)
			});
		},
		// 确认选择所属社区
		chooseAddress() {
			this.showChooseAddress = true;
		},
		cancelAddress() {
			this.showChooseAddress = false;
		},
		confirmAddress(e) {
			this.communityLable = e.value[0].label +"/"+ e.value[1].label +"/"+ e.value[2].label;
			this.registerForm.locationId = e.value[2].value;
			this.showChooseAddress = false;
		},
		changeAddress(e) {
		  const {
			  columnIndex,
			  value,
			  values, // values为当前变化列的数组内容
			  index,
			  // 微信小程序无法将picker实例传出来，只能通过ref操作
			  picker = this.$refs.uPicker
		  } = e
		  // 当第二列值发生变化时，变化第三列(后一列)对应的选项
		  if (columnIndex === 1) {
			  // picker为选择器this实例，变化第二列对应的选项
			  picker.setColumnValues(2, this.addressData[index])
		  }
		},
		
		// 注册方法
		async handleRegister() {
		  if (this.$Utils.isNull(this.registerForm.nickName)) {
		    this.$modal.msgError("请输入姓名")
		  } else if (!this.$Utils.checkPhone(this.registerForm.username)) {
		    this.$modal.msgError("手机号不正确")
		  } else if (this.$Utils.isNull(this.registerForm.password)) {
		    this.$modal.msgError("请输入您的密码")
		  } else if (this.$Utils.isNull(this.registerForm.confirmPassword)) {
		    this.$modal.msgError("请输入确认密码")
		  } else if (this.registerForm.password !== this.registerForm.confirmPassword) {
		    this.$modal.msgError("两次密码不一致")
		  } else if (this.$Utils.isNull(this.registerForm.code) && this.captchaEnabled) {
		    this.$modal.msgError("请输入验证码")
		  } else {
		    this.$modal.loading("注册中，请耐心等待...")
			this.registerForm.phonenumber = this.registerForm.username
		    this.register()
		  }
		},
		
      // 返回用户登录
      handleUserLogin() {
        this.$tab.navigateTo(`/pages/login_new`)
      },
      
      // 用户注册
      async register() {
        register(this.registerForm).then(res => {
          this.$modal.closeLoading()
          uni.showModal({
          	title: "系统提示",
          	content: "恭喜你，您的账号 " + this.registerForm.username + " 注册成功！",
          	success: function (res) {
          		if (res.confirm) {
					uni.redirectTo({ url: `/pages/login_new` });
          		}
          	}
          })
        }).catch(() => {
          if (this.captchaEnabled) {
            this.getCode()
          }
        })
      },
    }
  }
</script>

<style lang="scss">
  page {
    background-color: #ffffff;
  }
  
  .xrequired:before {
	  content: '*';
	  color: red;
	  font-size: 12px;
	  margin-left: 12px;
	  margin-right: -6px;
  }
  
  .normal-login-container {
    width: 100%;

    .logo-content {
      width: 100%;
      font-size: 21px;
      text-align: center;
      padding-top: 8%;
	  height: 100rpx;
      image {
        border-radius: 4px;
      }

      .title {
        margin-left: 10px;
      }
    }

    .login-form-content {
      text-align: center;
      margin: 10px auto;
      margin-top: 8%;
      width: 80%;

      .input-item {
        margin: 14px auto;
        background-color: #f5f6f7;
        height: 45px;
        border-radius: 20px;

        .icon {
          font-size: 38rpx;
          margin-left: 10px;
          color: #999;
        }

        .input {
          width: 100%;
          font-size: 14px;
          line-height: 20px;
          text-align: left;
          padding-left: 15px;
        }
      }

      .register-btn {
        margin-top: 20px;
        height: 45px;
      }

      .xieyi {
        color: #333;
        margin-top: 20px;
		padding-bottom: 20px;
      }
      
      .login-code {
        height: 38px;
        float: right;
      
        .login-code-img {
          height: 38px;
          position: absolute;
          margin-left: 10px;
          width: 200rpx;
        }
      }
    }
  }

</style>
